#!/usr/bin/env python
#coding:utf-8
#Code by Mango
#Created Time: Sat 19 Jul 2014 11:31:08 AM CST

#服务端:用来接受客户端发来的消息并进行处理

import SocketServer
import datetime
import pickle
from libs.geColor import *
from libs.geCache import *
from sqlite3 import *
import re
import sys

#pfile = 'h_dic.pkl'
localip = sys.argv[1]
#初始化
host_status = {}  #定义一个存储主机状态的空字典
f = open('cache/client.txt')  #打开主机列表文件
while True:
    line = f.readline().split()  #读取文件,把每一行用空格分成一个列表
    if len(line) == 0:break    #读到空之后跳出循环
    host_status[line[0]] = []   #{"ip地址":[列表]}  初始化主机状态字典
f.close()

class myMonitorHandler(SocketServer.BaseRequestHandler):  #继承SocketServer.BaseRequestHandler
    def handle(self):  #
        recv_data = self.request.recv(1024)  #接受的数据
        if self.client_address[0] == localip:   #如果是本机发送的包则pickle.dump数据
            pfile = 'h_dic.pkl'
            fp = file(pfile, 'wb')
            pickle.dump(host_status, fp)
            fp.close()
        if self.client_address[0] in host_status.keys():    #发送消息的客户端ip如果属于host_status的key列表
            if recv_data != "up":
                status_list = recv_data.split(",")  #把字符串转换成列表
                a = status_list[0]    # cpu
                i = a.replace('"','')
                b = str(int(status_list[1]) / 1024) + 'M'    # mem
                c = str(int(status_list[2]) / 1024) + 'M'    # mem free
                d = str(int(status_list[3]) / 1024) + 'M'    # swap
                e = str(int(status_list[4]) / 1024) + 'M'    # swap free
                f = str(int(status_list[5]) / 1024) + 'M'    # disk
                g = str(int(status_list[6]) / 1024) + 'M'    # disk free
                h = re.findall(r'\)\s(.*)',status_list[7])[0]    #day
                #h = status_list[7]
                j = status_list[8] # uptime
                conn = connect(gedb)  # 连接sqldb,没有则新建一个
                # id integer primary key,ip text,cpu text,mem text,swap text,disk text,uptime text
                conn.execute("update server set cpu='%s',mem='%s',memfree='%s',swap='%s',swapfree='%s',disk='%s',diskfree='%s',day='%s',uptime='%s' where ip = '%s'"%(i,b,c,d,e,f,g,h,j,self.client_address[0]))
                conn.commit()    # 执行
                conn.close()    # 关闭连接
            else:
                host_status[self.client_address[0]].append((datetime.datetime.now(),recv_data))   #就把发送时间和数据放入字典的列表中
                #print "From %s : %s %s" % (self.client_address, datetime.datetime.now(), recv_data)
        else:
            #print "sorry,ip %s is not in the monitor" % self.client_address[0]
            pass    #不做任何处理,今后可以做个iptables的禁止处理
			#或者直接在初始化阶段就将允许列表加入iptables其他ip禁止访问端口
        #for t,m in host_status.items():
            #print t,m  #输出内容的,可以注释掉

if __name__ == "__main__":
    host,port = '', 18000
    server = SocketServer.ThreadingTCPServer((host,port),myMonitorHandler)
    server.serve_forever()
